﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using up6.db.database;
using up6.db.model;
using up6.db.sql;
using up6.db.utils;
using up6.sql;
using up6.utils;

namespace up6.filemgr.app
{
    /// <summary>
    /// 文件夹相关的操作
    /// </summary>
    public class DbFolder
    {
        public DbFolder()
        {
        }

        /// <summary>
        /// 构建路径
        /// </summary>
        /// <param name="fd"></param>
        /// <returns></returns>
        public List<FileInf> build_path(JObject fdCur)
        {
            var id = fdCur["id"].ToString().Trim();
            var pid = fdCur["pid"].ToString().Trim();
            var pathRel = fdCur["pathRel"].ToString().Trim();
            List<FileInf> rels = new List<FileInf>();

            //根目录
            if (pathRel=="/")
            {
                var f = new FileInf();
                f.pathSvr = "/";
                f.nameLoc = "根目录";
                rels.Add(f);

                var dir = new FileInf();
                dir.pathRel = pathRel;
                int rpos = dir.pathRel.LastIndexOf("/");
                dir.nameLoc = dir.pathRel.Substring(rpos + 1);
                rels.Add(dir);
            }
            //子目录
            else {
                // /a/b/c/d/e=>,a,b,c,d,e
                int pos = 0;
                while ( (pos = pathRel.IndexOf("/", pos)) !=-1)
                {
                    var dir = new FileInf();
                    dir.pathRel = pathRel.Substring(0, pos);                    
                    dir.nameLoc = PathTool.getName(dir.pathRel);
                    if (string.IsNullOrEmpty(dir.nameLoc)) dir.nameLoc = "根目录";
                    if (string.IsNullOrEmpty(dir.pathRel)) dir.pathRel = "/";
                    rels.Add(dir);
                    pos++;
                }
                var f = new FileInf();
                f.pathRel = pathRel;
                f.nameLoc = PathTool.getName(f.pathRel);
                rels.Add(f);
            }
            return rels;
        }

        public bool exist_same_folder(string pathRel)
        {
            DBConfig cfg = new DBConfig();
            SqlWhereMerge swm = new SqlWhereMerge();
            swm.equal("f_pathRel", pathRel);
            swm.equal("f_deleted", 0);

            string sql = string.Format("select f_id from up6_files where {0} " +
                                        " union select f_id from up6_folders where {0}", swm.to_sql());

            SqlExec se = cfg.se();
            var fid = (JArray)se.exec("up6_files", sql, "f_id", string.Empty);
            return fid.Count > 0;
        }
    }
}